﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using Nii.JSON;
using System.Data;

namespace jslinttoolkit
{
    public partial class _default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData(true);
            }
        }

        #region LoadData

        private void LoadData(bool showAllErrors)
        {
            btnExpandAll.OnClientClick = Tree1.GetExpandAllNodesReference();
            btnCollapseAll.OnClientClick = Tree1.GetCollapseAllNodesReference();


            string treestr = GetFileContent("~/data/json/tree.json");

            List<string> treePathList = new List<string>();
            ResolveMenuTree(new JSONArray(treestr), treePathList, showAllErrors, Tree1.Nodes);
        }

        private string GetFileContent(string path)
        {
            string treestr = String.Empty;
            using (StreamReader sr = new StreamReader(Server.MapPath(path)))
            {
                treestr = sr.ReadToEnd();
            }
            return treestr;
        }

        #region temp

        //private void ResolveMenuTree2(JSONArray ja, List<string> treePathList, bool showAllErrors, ExtAspNet.TreeNodeCollection nodes)
        //{
        //    for (int i = 0; i < ja.Count; i++)
        //    {
        //        JSONObject kid = ja[i] as JSONObject;
        //        string name = kid.getString("name");

        //        // 当前路径，如果basePath存在说明是根目录
        //        if (kid.has("basePath"))
        //        {
        //            treePathList.Add(kid.getString("basePath"));
        //        }
        //        else
        //        {
        //            treePathList.Add(name);
        //        }
        //        string currentPath = GetTreePath(treePathList);


        //        string type = kid.getString("type");

        //        // 如果文件夹中没有文件，则不添加此文件夹
        //        if (type == "folder" && kid.getInt("fileCount") == 0)
        //        {
        //            treePathList.RemoveAt(treePathList.Count - 1);
        //            continue;
        //        }

        //        ExtAspNet.TreeNode node = new ExtAspNet.TreeNode();
        //        nodes.Add(node);
        //        node.Text = name;

        //        node.Text = String.Format("<span qtip=\"{0}\">{1}</span>", currentPath, node.Text);

        //        if (type == "folder")
        //        {
        //            node.SingleClickExpand = true;

        //            ResolveMenuTree2(kid.getJSONArray("kids"), treePathList, showAllErrors, node.Nodes);
        //        }
        //        else
        //        {
        //            node.Leaf = true;
        //        }

        //        treePathList.RemoveAt(treePathList.Count - 1);
        //    }
        //} 

        #endregion

        private void ResolveMenuTree(JSONArray ja, List<string> treePathList, bool showAllErrors, ExtAspNet.TreeNodeCollection nodes)
        {
            for (int i = 0; i < ja.Count; i++)
            {
                JSONObject kid = ja[i] as JSONObject;
                string name = kid.getString("name");

                // 当前路径，如果basePath存在说明是根目录
                if (kid.has("basePath"))
                {
                    treePathList.Add(kid.getString("basePath"));
                }
                else
                {
                    treePathList.Add(name);
                }
                string currentPath = GetTreePath(treePathList);

                // 获取JSLint错误数
                JSONArray errors = kid.getJSONArray("errors");
                int errorCount = errors.getInt(0);
                int criticalErrorCount = errors.getInt(1);
                if (showAllErrors)
                {
                    if (errorCount > 0)
                    {
                        name += String.Format(" ({0})", errorCount);
                    }
                }
                else
                {
                    if (criticalErrorCount > 0)
                    {
                        name += String.Format(" ({0})", criticalErrorCount);
                    }
                }

                string type = kid.getString("type");

                // 如果文件夹中没有文件，则不添加此文件夹
                if (type == "folder" && kid.getInt("fileCount") == 0)
                {
                    treePathList.RemoveAt(treePathList.Count - 1);
                    continue;
                }

                ExtAspNet.TreeNode node = new ExtAspNet.TreeNode();
                nodes.Add(node);
                node.Text = name;
                //node.ToolTip = currentPath;

                // 节点的显示颜色
                string style = "";
                if (showAllErrors)
                {
                    if (errorCount == 0)
                    {
                        style = "color:green;";
                    }
                    else
                    {
                        if (criticalErrorCount == 0)
                        {
                            style = "color:#FF9900;";
                        }
                        else
                        {
                            style = "color:#FF0000;";
                        }
                    }
                }
                else
                {
                    if (criticalErrorCount != 0)
                    {
                        style = "color:#FF0000;";
                    }
                    else
                    {
                        style = "color:green;";
                    }
                }

                node.Text = String.Format("<span qtip=\"{2}\" style=\"{0}\">{1}</span>", style, node.Text, currentPath);


                if (type == "folder")
                {
                    node.SingleClickExpand = true;

                    ResolveMenuTree(kid.getJSONArray("kids"), treePathList, showAllErrors, node.Nodes);
                }
                else
                {
                    node.Leaf = true;

                    if (showAllErrors)
                    {
                        if (errorCount != 0)
                        {
                            node.EnablePostBack = true;
                            node.CommandName = currentPath;
                        }
                    }
                    else
                    {
                        if (criticalErrorCount != 0)
                        {
                            node.EnablePostBack = true;
                            node.CommandName = currentPath;
                        }
                    }
                }

                treePathList.RemoveAt(treePathList.Count - 1);
            }
        }

        private string GetTreePath(List<string> treePath)
        {
            string path = String.Empty;
            foreach (string node in treePath)
            {
                path += node + "/";
            }
            return path.TrimEnd('/');
        }
        #endregion

        #region Events

        protected void Grid1_PreRowDataBound(object sender, ExtAspNet.GridPreRowEventArgs e)
        {
            //DataRow row = e.DataItem as DataRow;
            //if (row != null)
            //{
            //    int level = Convert.ToInt32(row["level"]);
            //    string style = String.Empty;
            //    if (level == 1)
            //    {
            //        style = "color:#FF0000;";
            //    }
            //    else
            //    {
            //        style = "color:#FF9900;";
            //    }

            //    foreach (ExtAspNet.GridColumn column in Grid1.Columns)
            //    {
            //        ExtAspNet.BoundField field = column as ExtAspNet.BoundField;
            //        field.DataFormatString = "<span style=\"" + style + "\">{0}</span>";
            //    }
            //}
        }

        protected void Grid1_RowDataBound(object sender, ExtAspNet.GridRowEventArgs e)
        {
            // DataItem是行的数据源，
            // 如果数据源是DataTable/DataView/DataSet，则e.DataItem是DataRow
            // 如果数据源是List<MyClass>，则e.DataItem是MyClass
            // e.Values 是实际赋予此行每列的值，可以修改

            DataRow row = e.DataItem as DataRow;
            if (row != null)
            {
                int level = Convert.ToInt32(row["level"]);
                string style = String.Empty;
                if (level == 1)
                {
                    style = "color:#FF0000;";
                }
                else
                {
                    style = "color:#FF9900;";
                }

                for (int i = 0; i < e.Values.Length; i++)
                {
                    e.Values[i] = String.Format("<span style=\"{0}\">{1}</span>", style, e.Values[i]);
                }
            }
        }

        protected void Tree1_NodeCommand(object sender, ExtAspNet.TreeCommandEventArgs e)
        {
            string fileName = e.CommandName.Replace("/", "_");

            if (ViewState["CurrentFileName"] != null && ViewState["CurrentFileName"].ToString() == fileName)
            {
                return;
            }
            ViewState["CurrentFileName"] = fileName;

            string errorstr = GetFileContent(String.Format("~/data/errors/{0}.json", fileName));

            JSONArray ja = new JSONArray(errorstr);

            DataTable table = new DataTable();
            table.Columns.Add("level", typeof(Int32));
            table.Columns.Add("line", typeof(Int32));
            table.Columns.Add("character", typeof(Int32));
            table.Columns.Add("reason", typeof(String));
            table.Columns.Add("evidence", typeof(String));

            foreach (JSONArray error in ja.getArrayList())
            {
                DataRow row = table.NewRow();
                table.Rows.Add(row);

                row[0] = Convert.ToInt32(error[0]);
                row[1] = Convert.ToInt32(error[1]);
                row[2] = Convert.ToInt32(error[2]);
                row[3] = error[3].ToString();
                row[4] = error[4].ToString();
            }

            Grid1.DataSource = table;
            Grid1.DataBind();


            string showSourceScript = "(function(){getMainWindow().loadJS('data/source/" + fileName + "');}).defer(10);";
            ExtAspNet.PageContext.RegisterStartupScript(showSourceScript);
        }

        protected void btnCriticalErrors_Click(object sender, EventArgs e)
        {
            Tree1.ClearNodes();

            if (btnCriticalErrors.Pressed)
            {
                LoadData(false);
            }
            else
            {
                LoadData(true);
            }
        }

        #endregion
    }
}
